package a51qindian.com.comprehensive.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.li.interfaces.OnItemClickListener;
import com.li.utils.ToastUtil;
import com.li.widget.DoubleTextView;
import com.li.widget.MultipleLayout;
import com.li.widget.TopNavigationBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.adapter.StaffAdapter;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.items.LinearItemDecoration;
import a51qindian.com.comprehensive.model.CountBaseModel;
import a51qindian.com.comprehensive.model.StaffInfo;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import a51qindian.com.comprehensive.util.SpUtil;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/9/12 0012
 * Description: 员工管理
 */

public class CityStaffManagerActivity extends QDBaseActivity {


    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.recycler_staff)
    RecyclerView mRecyclerStaff;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;
    @BindView(R.id.dtv_num)
    DoubleTextView mDtvNum;

    private List<StaffInfo> mStaffInfoList;
    private StaffAdapter mStaffAdapter;
    private String mUid;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_city_staff_manager;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        setSmartRefreshLayout(mLayoutRefresh);
        mStaffInfoList = new ArrayList<>();
        mUid=SpUtil.getUserInfo(CityStaffManagerActivity.this, SpUtil.USER_ID);
        mStaffAdapter = new StaffAdapter(this);
        mRecyclerStaff.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerStaff.setAdapter(mStaffAdapter);
        mRecyclerStaff.addItemDecoration(new LinearItemDecoration());
        mStaffAdapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int pos) {
                AlertDialog.Builder builder = new AlertDialog
                        .Builder(CityStaffManagerActivity.this)
                        .setTitle("操作")
                        .setItems(new String[]{"拨打电话", "删除该员工"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        tel(mStaffInfoList.get(pos).getMobile());
                                        break;
                                    case 1:
                                        showDeleteConfirmDialog(CityStaffManagerActivity.this,pos);
                                        break;
                                }
                            }
                        })
                        .setPositiveButton("关闭", null);
                builder.create().show();

            }
        });
    }


    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        showStaffList(mUid,String.valueOf(mPage+1));
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        showStaffList(mUid,"0");

    }

    @Override
    public void onFunctionImgListener(View view) {
        super.onFunctionImgListener(view);
        startActivity(new Intent(CityStaffManagerActivity.this, AddStaffActivity.class));
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPage=0;
        mIsRefresh=true;
        showStaffList(mUid,String.valueOf(mPage));
    }

    private void tel(String phone) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + phone));
        startActivity(intent);
    }

    private void showDeleteConfirmDialog(Context context, final int pos) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle("提示")
                .setMessage("是否确认删除该员工")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteStaff(mUid, mStaffInfoList.get(pos).getUid(),pos);
                    }
                });
        builder.create().show();
    }

    private void showStaffList(String uid, final String page) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("page",page);
        ObservableHelper.createObservable(RetrofitCreator.createService().staffList(map))
                .subscribe(new SelectorObserver<CountBaseModel<List<StaffInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                        ToastUtil.showToast(CityStaffManagerActivity.this, info);
                    }

                    @Override
                    protected void onSuccess(CountBaseModel<List<StaffInfo>> listBaseModel) {
                        mLayoutContent.onSuccess();
                        if (mIsRefresh) {
                            mPage=0;
                            mStaffInfoList.clear();
                            mLayoutRefresh.setLoadmoreFinished(false);
                        }else {
                            mPage++;
                        }
                        stopRefreshLoad();
                        List<StaffInfo> staffInfoList = listBaseModel.getData();
                        if (!mIsRefresh&&staffInfoList.size()< Const.DEFAULT_PAGE_SIZE) {
                            mLayoutRefresh.setLoadmoreFinished(true);
                        }
                        mStaffInfoList.addAll(staffInfoList);
                        mStaffAdapter.setStaffInfoList(mStaffInfoList);

                        mDtvNum.setTxtRight(listBaseModel.getCount());
                    }
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                    }
                });
    }

    private void deleteStaff(String uid, String staffId, final int currentPos) {
        mLayoutContent.onLoadingWithContent("正在删除");
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("uu_id", staffId);
        ObservableHelper.createObservable(RetrofitCreator.createService().deleteStaff(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object=new JSONObject(s);
                            if (object.getInt("code")==1) {
                                mStaffInfoList.remove(currentPos);
                                mStaffAdapter.notifyItemRemoved(currentPos);

                                mDtvNum.setTxtRight(String.valueOf(
                                        Integer.parseInt(mDtvNum.getTxtRight())-1));
                            }
                            ToastUtil.showToast(CityStaffManagerActivity.this,object.getString("info"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        ToastUtil.showToast(CityStaffManagerActivity.this,e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
